package com.zr.service.sys.impl;

import com.zr.dao.sys.SysAuthDao;
import com.zr.dao.sys.SysRoleAuthDao;
import com.zr.exception.BusinessException;
import com.zr.exception.ValidateException;
import com.zr.service.sys.SysAuthService;
import com.zr.utils.TokenUtil;
import com.zr.vo.sys.SysAuth;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 权限操作 服务层实现类
 */
@Service
public class SysAuthServiceImpl implements SysAuthService {

    @Resource
    private SysAuthDao sysAuthDao;

    @Resource
    private SysRoleAuthDao sysRoleAuthDao;

    @Resource
    private TokenUtil tokenUtil;

    /**
     * 查询所有权限
     *
     * @return
     */
    @Override
    public List<SysAuth> list() {
        return sysAuthDao.selectByPid(null);
    }

    /**
     * 删除权限
     *
     * @param id 权限ID
     * @return
     * @throws BusinessException
     */
    @Transactional
    @Override
    public int remove(Integer id) throws BusinessException {
        List<SysAuth> sysAuthList = sysAuthDao.selectByPid(id);
        if (sysAuthList.size() != 0) throw new BusinessException("请移除所有子菜单后再删除本菜单");
        //删除角色权限中间表
        sysRoleAuthDao.deleteByAuthId(id);
        return sysAuthDao.deleteByPrimaryKey(id);
    }

    /**
     * 新增权限
     *
     * @param sysAuth
     * @return
     */
    @Transactional
    @Override
    public int add(SysAuth sysAuth) {
        String index = "";
        List<SysAuth> sysAuthList;
        if (sysAuth.getPid() == null) {
            sysAuthList = sysAuthDao.selectByPidOrder(null);
            index = String.valueOf(Integer.parseInt(sysAuthList.get(sysAuthList.size() - 1).getMenuIndex()) + 1);
        } else {
            index = getIndex(sysAuth.getPid());
        }
        sysAuth.setMenuIndex(index);
        sysAuth.setCreateId(tokenUtil.currentUserId());
        sysAuth.setCreateTime(new Date());
        return sysAuthDao.insertSelective(sysAuth);
    }

    /**
     * 编辑权限
     *
     * @param sysAuth
     * @return
     * @throws ValidateException 参数检查异常
     */
    @Transactional
    @Override
    public int edit(SysAuth sysAuth) throws ValidateException {
        if (sysAuth.getId().equals(sysAuth.getPid())) {
            throw new ValidateException("上级菜单不可以设置成自己");
        }
        SysAuth oSysAuth = sysAuthDao.selectByPrimaryKey(sysAuth.getId());
        if (oSysAuth.getPid() != null) {
            if (sysAuth.getPid() == null) {
                throw new ValidateException("子菜单不可以变为父菜单");
            } else if (sysAuth.getPid() != oSysAuth.getPid()) {
                sysAuth.setMenuIndex(getIndex(sysAuth.getPid()));
            }
        }
        sysAuth.setModifyId(tokenUtil.currentUserId());
        sysAuth.setModifyTime(new Date());
        return sysAuthDao.updateByPrimaryKeySelective(sysAuth);
    }

    /**
     * 查询当前用户权限（base）
     *
     * @return
     */
    @Override
    public List<SysAuth> listByCurrentUser() {
        return sysAuthDao.listByCurrentUser(tokenUtil.currentUserId());
    }

    /***
     * 查询当前用户权限（带子权限）
     *
     * @return
     */
    @Override
    public List<SysAuth> getCurentAuths() {
        String userId = tokenUtil.currentUserId();
        List<SysAuth> sysAuthList = sysAuthDao.authListByUserId(userId);
        return sysAuthList;
    }

    /***
     * 获取所有父级权限
     *
     * @return
     */
    @Override
    public List<SysAuth> getParents() {
        return sysAuthDao.getParents();
    }

    /***
     * 根据父权限id获取新增子权限的index
     *
     * @param pid
     * @return
     */
    private String getIndex(Integer pid) {
        List<SysAuth> sysAuthList = sysAuthDao.selectByPidOrder(pid);
        String index = "";
        if (sysAuthList.size() == 0) {
            SysAuth parent = sysAuthDao.selectByPrimaryKey(pid);
            index = parent.getMenuIndex() + "-1";
        } else {
            SysAuth last = sysAuthList.get(sysAuthList.size() - 1);
            String lastIndex = last.getMenuIndex();
            String fIndex = lastIndex.split("-")[0];
            String sIndex = lastIndex.split("-")[1];
            index = fIndex + "-" + (Integer.parseInt(sIndex) + 1);
        }
        return index;
    }

}
